package com.henz.web.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceConfig;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.ImplicitTransactionManagementPolicy;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.henz.web.domain.HenzUser;
import com.henz.web.service.HenzUserService;
import com.henz.web.util.ConvertUtil;
import com.henz.web.variable.HenzDB;

public class HenzUserServiceImpl implements HenzUserService {
	
	private Log logger = LogFactory.getLog(this.getClass());
	
	private static DatastoreServiceConfig config = 
			DatastoreServiceConfig.Builder.withImplicitTransactionManagementPolicy(ImplicitTransactionManagementPolicy.NONE);
	private static DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(config);
	

	@Override
	public List<Map<String, Object>> saveUser(List<Map<String, Object>> userList) {
		
        Query query = null;
        
        Filter userFilter = null;
        Iterator<Entity> entityIt = null;
        
        Entity userEntity = null;
        Entity curEntity = null;
		Key keyObj = null;
		
        logger.info("saveUser=========");
        logger.info(userList);
        if(userList != null){
			datastore = DatastoreServiceFactory.getDatastoreService();
	        for(Map<String, Object> user:userList){
	        	logger.info("saveUser user=========");
	            logger.info(user);
	            logger.info("saveUser user=========");
	            userFilter = new FilterPredicate("email",
						FilterOperator.EQUAL, user.get("email"));
	            
	            query = new Query(HenzDB.HENZ_USER).setFilter(userFilter).setKeysOnly();
	            
	            entityIt = datastore.prepare(query).asIterator();
	            logger.info("saveUser check[" + entityIt + "]");
	            if(entityIt != null && entityIt.hasNext()){
	            	logger.info("saveUser check[exists]");
	            }else if(user.get( "email" ) != null){
	            	logger.info("saveUser check[not exists]");
	            	userEntity = ConvertUtil.toEntity(HenzDB.HENZ_USER, "email", user);
	        		if( userEntity != null ){
	        			keyObj = userEntity.getKey();
	        			try {
	        				curEntity = datastore.get(keyObj);
						} catch (EntityNotFoundException e) {
						}
	        			if(curEntity == null){
	        				datastore.put(userEntity);
	        			}
	        			datastore.put(userEntity);
	        		}
	        	}
			}
		}
        logger.info("saveUser=========");
		return userList;
	}

	@Override
	public void deleteUser(List<Map<String, Object>> userList) {
		/*
		Query query = null;
		datastore = DatastoreServiceFactory.getDatastoreService();
		//datastore.delete(arg0);
		query = new Query(HenzDB.HENZ_USER).addSort("date", Query.SortDirection.DESCENDING);
		*/
	}

	@Override
	public void deleteUserById(Long id) {
		/*
		Query query = null;
		datastore = DatastoreServiceFactory.getDatastoreService();
		query = new Query(HenzDB.HENZ_USER).addSort("date", Query.SortDirection.DESCENDING);
		userResult = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(10));
		*/
		
		//datastore.delete(arg0);

	}

	@Override
	public HenzUser findUserById(Long id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Map<String, Object>> findAllUsers() {
		logger.info("findAllUsers=========");
		
		Query query = null;
		List<Entity> userResult = null;
		List<Map<String, Object>> userList = null;
		
		datastore = DatastoreServiceFactory.getDatastoreService();
		query = new Query(HenzDB.HENZ_USER)
			//.addSort("date", Query.SortDirection.DESCENDING)
			;
		userResult = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(10));
	    
		userList = new ArrayList<Map<String, Object>>();
		logger.info("findAllUsers[" + userResult + "]");
		for( Entity userEntity : userResult ){
			userList.add(ConvertUtil.toMap(userEntity));
		}
		
		logger.info("findAllUsers=========");
		return userList;
	}

}
